package org.swust.monitor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.swust.monitor.entity.SysUser;
import org.swust.monitor.entity.dto.SysUserDto;
import org.swust.monitor.entity.vo.QSysUser;
import org.swust.monitor.mapper.SysUserMapper;
import org.swust.monitor.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author hanxinxin
 * @since 2024-12-31
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Override
    public List<SysUser> listByNickname(String name) {
        if (name == null) {
            return this.list();
        } else {
            //QueryWrapper queryWrapper =new QueryWrapper<SysUser>().like("nickname",name);
            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<SysUser>().like(SysUser::getNickname, name);
            return this.list(queryWrapper);
        }
    }

    @Override
    public List<SysUser> list(QSysUser qSysUser) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<SysUser>();

        queryWrapper.like(qSysUser.getUsername() != null && qSysUser.getUsername().isEmpty(),
                        SysUser::getUsername, qSysUser.getUsername())
                .eq(qSysUser.getDeptId() != null, SysUser::getDeptId, qSysUser.getDeptId())
                .eq(qSysUser.getRoleId() != null, SysUser::getRoleId, qSysUser.getRoleId())
                .ge(qSysUser.getBirthdayStart() != null, SysUser::getBirthday, qSysUser.getBirthdayStart());

        return this.list(queryWrapper);
    }


    @Override
    public boolean updateStatusById(Integer userId, boolean status) {
        return baseMapper.updateStatusById(userId, status) > 0 ? true : false;
    }

    @Override
    public Page<SysUserDto> pageUser(Page<SysUserDto> page, QSysUser qSysUser) {
        return baseMapper.pageUser(page, qSysUser);
    }

    @Override
    public boolean save(SysUser entity) {
        entity.setPassword(bCryptPasswordEncoder.encode("123456"));
        return super.save(entity);
    }

    private static BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
    @Override
    public int resetPassword(Integer userId) {
        String resetPwd="123456";
        resetPwd=bCryptPasswordEncoder.encode(resetPwd);
        SysUser user=new SysUser();
        user.setPassword(resetPwd);
        user.setUserId(userId);
        return baseMapper.updateById(user);
    }

}
